import md5 from 'md5';
import React, { useEffect } from 'react';

import api from '@/api';
import store from '@/reducers';
import { getUserProfits } from '@/reducers/user';
import { getRandom32 } from '@/utils/common';
import req from '@/utils/req';
import useSetState from '@/utils/useSetState';

export type RightType = {
  number: number;
  id: number;
  type: 'coupon' | 'member';
  name: string;
  unit: string;
  unit_zh: string;
  tag: string;
  amount: string;
  pay_amount: string;
  desc: string;
  sort: number;
  btn: string;
  rights: string[];
};
type Props = {
  goodItem?: RightType;
  item?: {
    id: number;
    order_sn: string;
    goods_id: number;
    goods_name: string;
    pay_amount: string;
    order_expire_time: string;
    pay_time: string;
    status: number;
    bill_request_status: number;
  };

  children: React.ReactElement;
};
type OrderResultType = {
  id: number;
  order_sn: string;
  user_id: string;
  goods_id: number;
  total_amount: number;
  pay_amount: number;
  pay_type: string;
  source_type: string;
  status: 0;
};

const PayModal: React.FC<Props> = ({ children, item, goodItem }) => {
  const [{ open, loading, qrcode, orderId }, setState] = useSetState({
    open: false,
    loading: false,
    qrcode: 'qr',
    orderId: 0,
  });

  async function orderClick() {
    if (loading) {
      return;
    }
    setState({ loading: true });

    try {
      let myId = 0;
      if (item) {
        myId = item.id;
      } else {
        const data = await req.post<OrderResultType>(api.createOrder, {
          goods_id: goodItem?.id,
          pay_type: 'wechat',
          source: 'app',
        });
        myId = data.id;
      }

      const { qrcode, prepay_id } = await req.post<{
        qrcode: string;
        prepay_id: string;
      }>(api.orderWxPay, {
        order_id: myId,
        trade_type: 'JSAPI',
      });

      const appId = 'wxe25860e76738cf77';
      const nonceStr = getRandom32();
      const timeStamp = parseInt(Date.now() / 1000 + '') + '';
      const _package = `prepay_id=${prepay_id}`;
      const signType = 'MD5';
      const paycode = `appId=${appId}&nonceStr=${nonceStr}&package=${_package}&signType=${signType}&timeStamp=${timeStamp}&key=RuiYanShiJieBigDataMemberPay1234`;
      const paySign = (md5(paycode) as string).toUpperCase();
      console.log(paySign);
      // Taro.requestPayment({
      //   timeStamp,
      //   nonceStr,
      //   package: _package,
      //   signType,
      //   paySign,
      //   success() {
      //     checkData();
      //     function checkData() {
      //       req.post(api.queryPayResult, { order_id: myId }).then((data: any) => {
      //         if (data.status == 0) {
      //           setTimeout(() => {
      //             checkData();
      //           }, 2000);
      //         } else {
      //           Taro.showToast({ title: '支付成功' });
      //           Taro.showToast({ title: '支付成功', icon: 'success' });
      //           store.dispatch(getUserProfits());
      //           children.props.onClick && children.props.onClick();
      //         }
      //       });
      //     }
      //   },
      //   fail() {
      //     Taro.showToast({ title: '支付失败', icon: 'error' });
      //   },
      // });
      setState({ qrcode, orderId: myId });
    } catch (error) {
      console.log(error);
    } finally {
      setState({ loading: false });
    }
  }
  const btn = React.cloneElement(children, {
    onClick: orderClick,
  });

  useEffect(() => {
    function checkData() {
      req.post<{ status: number }>(api.queryPayResult, { order_id: orderId }).then((data) => {
        if (data.status == 0 && open) {
          setTimeout(() => {
            checkData();
          }, 2000);
        } else {
          setState({ open: false });
          // store.dispatch(getUser())
          store.dispatch(getUserProfits());
        }
      });
    }
    if (orderId && open) {
      checkData();
    }
  }, [orderId, qrcode, open, setState]);

  return <>{btn}</>;
};

export default PayModal;
